from appium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

def connect_app(platname='Android',platversion='7.1.2',dname='****',appname='com.tongshi.user.benben',appact='io.dcloud.PandoraEntryActivity',port=4723):


  #设置
  desire_caps=dict(
    platformName=platname,
    platformVersion=platversion,
    deviceName=dname,
    appPackage=appname,
    appActivity=appact,
    #重置设备的键盘
    noReset=True,   #记录session状态，如果登录过，或者做过初始化后续就不需要操作
    resetkeyboard=True, #重置输入的键盘
    unicodeKeyboard=True  #采用可以输入汉字的unicode编码
  )


  ##连接appuim的服务器地址
  url='http://127.0.0.1:%s/wd/hub'%port
  ##连接appuim的服务器
  driver=webdriver.Remote(url,desire_caps)
  return driver

def get_elements(driver,style,value):
  driver_wait=WebDriverWait(driver,2)
  element=driver_wait.until(lambda driver:driver.find_elements(by=style,value=value))
  return element


def get_element(driver,style,value):
  driver_wait=WebDriverWait(driver,2)
  element=driver_wait.until(lambda driver:driver.find_element(by=style,value=value))
  return element

def input_text(element,text):
  element.clear()
  element.send_keys(text)

#判断是否能够定位
def is_located(driver,style,value):
  try:
    element=get_element(driver=driver,style=style,value=value)
  except Exception as e:
    print('当前规则，定位不到元素-----》',value)
    print(e)
  else:
   return element

  finally:
    print('好的')

def handler_swipe(direction, driver):
  date=driver.get_window_size()
  x=date.get('width','cannot find width')
  y=date.get('height', 'cannot find height')
  if (x !='cannot find width') and (y !='cannot find height'):
    if direction == 'down':
      driver.swipe(x*0.5, y*0.3, x*0.5, y*0.8, 1000)
    elif direction == 'up':
      driver.swipe(x*0.5, y*0.8, x*0.5, y*0.3, 1000)
    elif direction == 'left':
      driver.swipe(x*0.8, y*0.5, x*0.3, y*0.5, 1000)
    elif direction == 'right':
      driver.swipe(x*0.3, y*0.5, x*0.8, y*0.5, 1000)
    else:
      print('----')